package org.example.projecttwo.controller.content;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.example.projecttwo.common.Result;
import org.example.projecttwo.common.utils.NewsNoGenerator;
import org.example.projecttwo.entity.dto.content.request.BatchNewsAuditDTO;
import org.example.projecttwo.entity.dto.content.request.ContentOffShelfDTO;
import org.example.projecttwo.entity.news.News;
import org.example.projecttwo.entity.dto.content.request.BatchOperationDTO;
import org.example.projecttwo.entity.dto.content.request.NewsAuditDTO;
import org.example.projecttwo.entity.dto.content.response.NewsDetailVO;
import org.example.projecttwo.service.Inews.INewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/news")
@Tag(name = "新闻管理", description = "新闻信息管理")
public class NewsController {

    @Autowired
    private INewsService newsService;

    @GetMapping("/list")
    @Operation(summary = "分页查询新闻列表", description = "分页查询新闻列表，支持状态筛选和时间范围筛选 -- 新闻管理")
    public Result<IPage<News>> listNews(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<News> page = new Page<>(current, size);
        IPage<News> result = newsService.pageByCondition(page, status, keyword, startTime, endTime);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取新闻详情", description = "根据新闻ID获取新闻详情，包含审核信息和统计数据 -- 新闻管理")
    public Result<NewsDetailVO> getNews(@PathVariable Long id) {
        NewsDetailVO news = newsService.getNewsDetail(id);
        return Result.success(news);
    }

    @PostMapping
    @Operation(summary = "新增新闻", description = "新增新闻，默认状态为草稿 -- 新闻管理")
    public Result<News> createNews(@Valid @RequestBody News news) {
        news.setStatus(0); // 0=草稿

        // 生成并设置新闻编号
        String newsNo = NewsNoGenerator.generateNewsNo();
        news.setNewsNo(newsNo);

        // 设置创建时间和更新时间
        news.setCreateTime(LocalDateTime.now());
        news.setUpdateTime(LocalDateTime.now());

        newsService.save(news);
        return Result.success(news);
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改新闻", description = "修改新闻信息 -- 新闻管理")
    public Result<News> updateNews(@PathVariable Long id, @Valid @RequestBody News news) {
        News existing = newsService.getById(id);
        if (existing == null) {
            return Result.error("新闻不存在");
        }
        // 已发布的新闻不可直接编辑
        if (existing.getStatus() == 2) {
            return Result.error("已发布新闻不可编辑，请先下架");
        }
        news.setId(id);
        newsService.updateById(news);
        return Result.success(newsService.getById(id));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除新闻", description = "根据新闻ID删除新闻，支持10天内恢复 -- 新闻管理")
    public Result<String> deleteNews(
            @PathVariable Long id,
            @Valid @RequestBody Map<String, Object> params) {
        Integer deleteReason = (Integer) params.get("reason");
        String deleteRemark = (String) params.get("remark");

        if (deleteReason == null) {
            return Result.error("请选择删除原因");
        }

        newsService.deleteNews(id, deleteReason, deleteRemark);
        return Result.success("删除成功，10天内可恢复");
    }

    @PutMapping("/{id}/submit-audit")
    @Operation(summary = "提交审核", description = "将新闻状态改为待审核，可指定发布策略 -- 新闻管理")
    public Result<String> submitAudit(
            @PathVariable Long id,
            @RequestParam Integer publishStrategy,
            @RequestParam(required = false) String customPublishTime) {
        newsService.submitAudit(id, publishStrategy, customPublishTime);
        return Result.success("提交审核成功");
    }

    @PutMapping("/{id}/cancel-audit")
    @Operation(summary = "取消审核", description = "将新闻从待审核状态撤回 -- 新闻管理")
    public Result<String> cancelAudit(@PathVariable Long id) {
        newsService.cancelAudit(id);
        return Result.success("取消审核成功");
    }

    @PutMapping("/{id}/publish")
    @Operation(summary = "发布新闻", description = "将新闻状态改为审核通过 -- 新闻管理")
    public Result<String> publishNews(@PathVariable Long id) {
        newsService.updateStatus(id, 2); // 2=审核通过
        return Result.success("发布成功");

    }

    @PutMapping("/{id}/unpublish")
    @Operation(summary = "下架新闻", description = "将新闻状态改为已下架，并记录下架原因 -- 新闻管理")
    public Result<String> unpublishNews(
            @PathVariable Long id,
            @Valid @RequestBody Map<String, Object> params) {  // 使用Map接收参数
        Integer offShelfReason = (Integer) params.get("reason");  // 对应选择框的下架原因

        if (offShelfReason == null) {
            return Result.error("请选择下架原因");
        }

        newsService.unpublishNews(id, offShelfReason);
        return Result.success("下架成功");
    }

    @PostMapping("/batch-publish")
    @Operation(summary = "批量发布新闻", description = "批量将新闻状态改为审核通过 -- 新闻管理")
    public Result<String> batchPublish(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }
        newsService.batchUpdateStatus(ids, 2);
        return Result.success("批量发布成功,共" + ids.size() + "条");
    }

    @PostMapping("/batch-unpublish")
    @Operation(summary = "批量下架新闻", description = "批量将新闻状态改为已下架，并记录下架原因 -- 新闻管理")
    public Result<String> batchUnpublish(
            @Valid @RequestBody BatchOperationDTO batchOperationDTO) {
        List<Long> ids = batchOperationDTO.getIds();
        Integer offShelfReason = batchOperationDTO.getReason();

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }
        if (offShelfReason == null) {
            return Result.error("请选择下架原因");
        }

        newsService.batchUnpublish(ids, offShelfReason);
        return Result.success("批量下架成功,共" + ids.size() + "条");
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除新闻", description = "批量删除新闻，支持10天内恢复 -- 新闻管理")
    public Result<String> batchDelete(
            @Valid @RequestBody BatchOperationDTO batchOperationDTO) {
        List<Long> ids = batchOperationDTO.getIds();
        Integer deleteReason = batchOperationDTO.getReason();
        String deleteRemark = batchOperationDTO.getRemark();

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }
        if (deleteReason == null) {
            return Result.error("请选择删除原因");
        }

        newsService.batchDelete(ids, deleteReason, deleteRemark);
        return Result.success("批量删除成功,共" + ids.size() + "条");
    }

    @GetMapping("/published-count")
    @Operation(summary = "获取已发布新闻数量", description = "统计已发布新闻的数量 -- 新闻管理")
    public Result<Integer> getPublishedCount() {
        int count = newsService.countPublishedNews();
        return Result.success(count);
    }

    @PutMapping("/{id}/audit")
    @Operation(summary = "审核新闻", description = "审核新闻并更新状态，记录审核信息 -- 新闻管理")
    public Result<String> auditNews(
            @PathVariable Long id,
            @Valid @RequestBody NewsAuditDTO auditDTO) {
        if (auditDTO.getAuditResult() == 3 && (auditDTO.getRejectReason() == null || auditDTO.getRejectReason().isEmpty())) {
            return Result.error("审核未通过时必须填写拒绝原因");
        }
        newsService.auditNews(id, auditDTO.getAuditResult(), auditDTO.getRejectReason());
        return Result.success(auditDTO.getAuditResult() == 2 ? "审核通过" : "审核未通过");
    }

    @PostMapping("/batch-audit")
    @Operation(summary = "批量审核新闻", description = "批量审核新闻并更新状态 -- 新闻管理")
    public Result<String> batchAudit(
            @Valid @RequestBody BatchNewsAuditDTO batchDTO) {
        List<Long> ids = batchDTO.getIds();
        Integer auditResult = batchDTO.getAuditResult();
        String rejectReason = batchDTO.getRejectReason();

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }

        if (auditResult == 3 && (rejectReason == null || rejectReason.isEmpty())) {
            return Result.error("审核未通过时必须填写拒绝原因");
        }

        newsService.batchAudit(ids, auditResult, rejectReason);
        return Result.success(auditResult == 2 ?
                "批量审核通过，共" + ids.size() + "条" :
                "批量审核未通过，共" + ids.size() + "条");
    }

    @GetMapping("/{id}/statistics")
    @Operation(summary = "获取新闻统计数据", description = "获取新闻的浏览、点赞、收藏等统计信息 -- 新闻管理")
    public Result<Map<String, Integer>> getNewsStatistics(@PathVariable Long id) {
        Map<String, Integer> stats = newsService.getNewsStatistics(id);
        return Result.success(stats);
    }

    @PutMapping("/{id}/view")
    @Operation(summary = "增加新闻浏览量", description = "记录新闻的浏览次数 -- 新闻管理")
    public Result<String> increaseViewCount(@PathVariable Long id) {
        newsService.increaseViewCount(id);
        return Result.success("浏览量记录成功");
    }

    @GetMapping("/drafts/{userId}")
    @Operation(summary = "获取指定用户新闻草稿", description = "获取指定用户的所有新闻草稿 -- 新闻管理")
    public Result<List<News>> getUserDrafts(@PathVariable Long userId) {
        if (userId == null || userId <= 0) {
            return Result.error("用户ID无效");
        }
        List<News> drafts = newsService.getUserDraftsByUserId(userId);
        return Result.success(drafts);
    }

    @DeleteMapping("/drafts/{id}")
    @Operation(summary = "删除新闻草稿", description = "删除指定的新闻草稿 -- 新闻管理")
    public Result<String> deleteDraft(@PathVariable Long id) {
        newsService.deleteDraft(id);
        return Result.success("草稿删除成功");
    }

    @GetMapping("/author/{userId}")
    @Operation(summary = "获取作者新闻", description = "获取指定作者发布的新闻 -- 新闻管理")
    public Result<IPage<News>> getAuthorNews(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<News> page = new Page<>(current, size);
        IPage<News> result = newsService.pageByAuthor(page, userId);
        return Result.success(result);
    }

    @GetMapping("/deleted/list")
    @Operation(summary = "获取已删除新闻列表", description = "分页查询已删除的新闻列表 -- 新闻管理")
    public Result<IPage<News>> listDeletedNews(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<News> page = new Page<>(current, size);
        IPage<News> result = newsService.pageDeletedNews(page, keyword);
        return Result.success(result);
    }

    @PostMapping("/deleted/restore")
    @Operation(summary = "恢复已删除新闻", description = "恢复指定的已删除新闻 -- 新闻管理")
    public Result<String> restoreDeletedNews(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }
        newsService.restoreDeletedNews(ids);
        return Result.success("恢复成功，共" + ids.size() + "条");
    }

    @PostMapping("/deleted/permanent")
    @Operation(summary = "永久删除新闻", description = "永久删除指定的已删除新闻，不可恢复 -- 新闻管理")
    public Result<String> permanentlyDeleteNews(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }
        newsService.permanentlyDeleteNews(ids);
        return Result.success("永久删除成功，共" + ids.size() + "条");
    }

    @PostMapping("/deleted/batch-restore")
    @Operation(summary = "批量恢复已删除新闻", description = "批量恢复指定的已删除新闻 -- 新闻管理")
    public Result<String> batchRestoreDeletedNews(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }
        newsService.restoreDeletedNews(ids);
        return Result.success("批量恢复成功，共" + ids.size() + "条");
    }

    @PostMapping("/deleted/batch-permanent")
    @Operation(summary = "批量永久删除新闻", description = "批量永久删除指定的已删除新闻，不可恢复 -- 新闻管理")
    public Result<String> batchPermanentlyDeleteNews(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一条新闻");
        }
        newsService.permanentlyDeleteNews(ids);
        return Result.success("批量永久删除成功，共" + ids.size() + "条");
    }
}